import { useHead, useSeoMeta } from '@unhead/vue'
import { storeToRefs } from 'pinia'
import { useAccountStore } from '@/store/account'
import { useAppStore } from '@/store/app'
import { useHeadStore } from '@/store/head'
import { locale } from '@/i18n'
import API from '@/http'
import { init } from '@/ws'

export async function useInit() {
  loadSeoHead()

  const appStore = useAppStore()
  const { initAppConfig, syncAllPaymentConfig } = appStore

  const accountStore = useAccountStore()
  const { isLogin } = storeToRefs(accountStore)
  const { resetUserData } = accountStore

  async function initUserData() {
    const data = await API.Auth.detail()
    resetUserData(data)
  }

  const initPromises = [initAppConfig() /* 初始化全域參數 */, syncAllPaymentConfig() /* 初始化所有金流 */]
  if (isLogin.value) {
    initPromises.push(initUserData() /* 初始化自己的資料 */)
  }

  await Promise.all(initPromises)

  // 初始化IM
  init()
}

function loadSeoHead() {
  const {
    title,
    description,
    keywords,
    ogTitle,
    ogDescription,
    ogUrl,
    ogType,
    ogImage,
    twitterTitle,
    twitterDescription,
    twitterImage,
    itemscope,
    itemtype,
  } = storeToRefs(useHeadStore())
  useSeoMeta({
    title,
    description,
    keywords,
    ogTitle,
    ogDescription,
    ogUrl,
    ogType,
    ogImage,
    twitterTitle,
    twitterDescription,
    twitterImage,
  })
  useHead({
    htmlAttrs: {
      lang: locale,
      itemscope,
      itemtype,
    },
  })
}
